<?php

namespace app\common\model;

use app\common\lib\Show;
use app\common\lib\Status;
use think\Exception;
use think\facade\Log;

class CouponReceive extends Base
{

    protected $deleteTime = "delete_time";

    /**
     * 返回用户领取次数
     * @param string $openid
     * @return CouponReceive|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserCouponReceiveByCount(string $openid = '')
    {
        return $this->field('count(*) as count')
            ->where('openid', $openid)
            ->find();
    }

    /**
     * @param array $where
     * @param string $field
     * @return CouponReceive|array|mixed|\think\Model|null
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserCouponReceiveIdByCount(array $where = [], string $field = '*')
    {
        return $this->field($field)
            ->where($where)
            ->find();
    }

    public function coupon()
    {
        return $this->belongsTo(CouponCoupon::class, 'coupon_id', 'id');
    }

    /**
     * @param $value
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getGetUserAttr($value)
    {
        $wechat = (new WeixinUser())->getWeixinUserByOpenid($value, 'id,nickName,realname,mobile,avatarUrl');
        if (!$wechat) {
            return [];
        }
        return $wechat->toArray();
    }

    /**
     * 查询用户未使用切正常的优惠券
     * 现在时间还没有到结束时间
     * @param string $openid
     * @return array
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     */
    public function getUserCouponReceiveByOpenidList(string $openid = ''): array
    {
        return $this
            ->where('end_time', ">", time())
            ->where('openid', $openid)
            ->where('status', 0)
            ->with('coupon')
            ->select()
            ->toArray();
    }
}